import { Component, OnInit } from '@angular/core';
import { Store } from '@ngxs/store';
import { SystemSelector } from '../../store/system/system.selector';
import { SystemAction } from '../../store/system/system.action';
import { AutoUnsubscribe } from 'ngx-auto-unsubscribe-decorator';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../../shared/shared.module';
import { RouterLink } from '@angular/router';
import { NzPopconfirmModule } from 'ng-zorro-antd/popconfirm';
import { invoke } from '@tauri-apps/api/tauri';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-backup',
  templateUrl: './backup.component.html',
  styleUrls: ['./backup.component.scss'],
  standalone: true,
  imports: [CommonModule, RouterLink, SharedModule, NzPopconfirmModule],
})
export class BackupComponent implements OnInit {
  list: any = [];
  @AutoUnsubscribe() loading$ = this.store.select(SystemSelector.loading);
  @AutoUnsubscribe() canBackup$ = this.store.select(SystemSelector.canBackup);
  @AutoUnsubscribe() defaultParam$ = this.store.select(SystemSelector.defaultParam);

  constructor(
      private store: Store,
      private message: NzMessageService,
  ) {
    this.store.select(SystemSelector.list).subscribe(r => this.list = r);
  }

  ngOnInit() {
    this.load();
  }

  load() {
    this.store.dispatch(new SystemAction.LoadBackupList());
  }

  revert(data: any) {
    this.store.dispatch(new SystemAction.Revert(data));
  }

  backup() {
    this.store.dispatch(new SystemAction.Backup());
  }

  delete(data: any) {
    console.log('delete', data.path);
    invoke('delete_file', {path: data.path}).then(() => {
      this.message.success(`还原成功！`);
    }).catch((error) => {
      this.message.error(`还原失败:${error}`);
    }).finally(() => {
      this.load();
    });
  }
}
